﻿using MediatR;
using Microsoft.AspNetCore.Mvc;
using WEBAPI.API.Application.Command;
using B.S.Base.Read.API.Dto;
using WEBAPI.ErroeCode;
using B.S.Base.Read.API.Application.Command;
using WEBAPI.Damoin;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using WEBAPI.API.Dto;
using B.S.BaseData.Common;
using Microsoft.AspNetCore.Authorization;
using OfficeOpenXml;
using System.IO;
using System.Security.Claims;

namespace B.S.Base.Read.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class MomentController : ControllerBase
    {
        IMediator mediator;
        ILogger<MomentController> logger;
        public MomentController(IMediator mediator, ILogger<MomentController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public Task<APIResult<LoginResultDto>> Login([FromQuery] LoginCommand login)
        {
            try
            {
               
                var result = mediator.Send(login);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 获取用户表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<List<AccountDto>>>> GetAccount([FromQuery] GetAccountCommand command)
        {
            try
            {
                var userId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                var userName = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 角色表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<List<RoleModel>>>> GetRole([FromQuery] GetRoleCommand command)
        {
            try
            {
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 部门
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<object>>> GetDept([FromQuery] GetDeptCommand command)
        {
            try
            {
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 角色的所有用户
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<APIResult<List<AccountModel>>> RoleUser([FromQuery] GetRoleaccountCommand command)
        {
            return mediator.Send(command);
        }
        /// <summary>
        /// 获取菜单表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<List<MenuModel>>>> GetMenu([FromQuery] GetMeunCommand command)
        {
            try
            {
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 是否有子集
        /// </summary>
        /// <param name="getQuery"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<bool>> getQuery([FromQuery] GetQueryPidCommand getQuery)
        {
            try
            {
                var result = await mediator.Send(getQuery);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 菜单树形
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<object>>> GetMument(int id)
        {
            GetMuneCommand command = new GetMuneCommand()
            {
                Rid = id
            };
            var result = await mediator.Send(command);
            return result;
        }
        /// <summary>
        /// 角色树形
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<RoleModel>>> GetMumentRole()
        {
            GetMenuRoleCommand command = new GetMenuRoleCommand();
            var result = await mediator.Send(command);
            return result;
        }
        /// <summary>
        /// 获取审批表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<List<ApproveModel>>>> GetApprove([FromQuery] GetApproveCommand getApproveCommand)
        {
            try
            {
                var result = await mediator.Send(getApproveCommand);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 部门下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<DeptModel>>> Getdeptmodel()
        {
            GetDeptmodelCommand command = new GetDeptmodelCommand();

            var result = await mediator.Send(command);
            return result;
        }
        /// <summary>
        /// 获取部门领导
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<object>>> Getdeptaccount([FromQuery] GetDeptAccountComand command)
        {

            var result = await mediator.Send(command);
            return result;
        }
        /// <summary>
        /// 用户角色权限
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<APIResult<List<Rolepermission>>> UserPermission([FromQuery] UserPermissionCommand command)
        {
            return mediator.Send(command);
        }
     /// <summary>
        /// 获取报表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<LeaveSummaryDto>>> GetFrom ([FromQuery] GetLeaveReportDynamicCommand command)
        {
            try
            {
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("异常处理" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 导出请假报表（Excel）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportLeaveReport([FromQuery] GetLeaveReportDynamicCommand command)
        {
            OfficeOpenXml.ExcelPackage.License.SetNonCommercialPersonal("Guyufan");
            var result = await mediator.Send(command);
            var data = result.Data ?? new List<LeaveSummaryDto>();

            using var package = new ExcelPackage();
            var worksheet = package.Workbook.Worksheets.Add("请假报表");

            // 表头
            worksheet.Cells[1, 1].Value = "用户ID";
            worksheet.Cells[1, 2].Value = "用户名";
            for (int i = 0; i < 12; i++)
            {
                worksheet.Cells[1, 3 + i].Value = $"{i + 1}月";
            }

            // 数据
            for (int i = 0; i < data.Count; i++)
            {
                worksheet.Cells[i + 2, 1].Value = data[i].UserId;
                worksheet.Cells[i + 2, 2].Value = data[i].UserName;
                for (int j = 0; j < 12; j++)
                {
                    worksheet.Cells[i + 2, 3 + j].Value = data[i].MonthlyHours[j];
                }
            }

            var stream = new MemoryStream(package.GetAsByteArray());
            stream.Position = 0;
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "请假报表.xlsx");
        }
    }
    }
